import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
import { useUserStore } from '@/store/user';
import Layout from '@/layout/index.vue';

// 公共路由
export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/404',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', hidden: true }
  },
  {
    path: '/403',
    component: () => import('@/views/error/403.vue'),
    meta: { title: '403', hidden: true }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        name: 'Dashboard',
        meta: { title: '首页', icon: 'House', affix: true }
      }
    ]
  }
];

// 动态路由，基于用户权限动态加载
export const asyncRoutes: RouteRecordRaw[] = [
  {
    path: '/system',
    component: Layout,
    redirect: '/system/user',
    meta: { title: '系统管理', icon: 'Setting', roles: ['admin'] },
    children: [
      {
        path: 'user',
        component: () => import('@/views/system/user/UserList.vue'),
        name: 'User',
        meta: { title: '用户管理', icon: 'User', roles: ['admin'] }
      },
      {
        path: 'role',
        component: () => import('@/views/system/role/RoleList.vue'),
        name: 'Role',
        meta: { title: '角色管理', icon: 'UserFilled', roles: ['admin'] }
      },
      {
        path: 'menu',
        component: () => import('@/views/system/menu/index.vue'),
        name: 'Menu',
        meta: { title: '菜单管理', icon: 'Menu', roles: ['admin'] }
      },
      // {
      //   path: 'role/menu-assignment',
      //   component: () => import('@/views/system/role/menu-assignment.vue'),
      //   name: 'MenuAssignment',
      //   meta: { title: '菜单权限分配', icon: 'Connection', roles: ['admin'], hidden: true }
      // }
    ]
  },
  {
    path: '/app',
    component: Layout,
    redirect: '/app/list',
    meta: { title: '应用管理', icon: 'Grid', roles: ['admin'] },
    children: [
      {
        path: 'list',
        component: () => import('@/views/app/list/index.vue'),
        name: 'AppList',
        meta: { title: '应用列表', icon: 'List', roles: ['admin'] }
      },
      {
        path: 'category',
        component: () => import('@/views/app/category/index.vue'),
        name: 'AppCategory',
        meta: { title: '应用分类', icon: 'Folder', roles: ['admin'] }
      },
      {
        path: 'audit',
        component: () => import('@/views/app/audit/index.vue'),
        name: 'AppAudit',
        meta: { title: '应用审核', icon: 'Check', roles: ['admin'] }
      }
    ]
  },
  // 404页面必须放在最后
  { path: '/:pathMatch(.*)*', redirect: '/404', meta: { hidden: true } }
];

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
});

// 白名单路由
const whiteList = ['/login', '/404', '/403'];

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - Simple Tools 管理系统` : 'Simple Tools 管理系统';

  const userStore = useUserStore();

  if (userStore.token) {
    if (to.path === '/login') {
      // 如果已登录，跳转到首页
      next({ path: '/' });
    } else {
      // 判断是否已获取用户信息
      if (!userStore.userInfo) {
        try {
          // 获取用户信息
          const res = await userStore.fetchUserInfo();
          if (!res) {
            throw new Error('获取用户信息失败')
          }

          // 动态添加路由
          asyncRoutes.forEach(route => {
            router.addRoute(route);
          });

          // 确保路由已添加完成
          next({ ...to, replace: true });
        } catch (error) {
          // 获取用户信息失败，清除token并跳转到登录页
          userStore.logout();
          next(`/login?redirect=${encodeURIComponent(to.path)}`);
        }
      } else {
        next();
      }
    }
  } else {
    // 未登录，判断是否在白名单中
    if (whiteList.includes(to.path)) {
      next();
    } else {
      // 跳转到登录页
      next(`/login?redirect=${encodeURIComponent(to.path)}`);
    }
  }
});

export default router;
